#include "libutil.h"
#include "llist.h"

#define ARGMAX 5

int strcmp_new(const void *str1, const void *str2);

int main(int argc, char *argv[])
{
   int c;
   FILE *input, *dict;
   int currw; 
   char *usage, *st;
   list_t *list;
   size_t *id;
   usage = "parse_words usage: parse_words -i input_file -d dictionary_file";

   while( (c = getopt(argc, argv, ":i:d:")) != -1 )
   {
     switch(c){
      
       case 'i':
         input = fopen(optarg, "r");
         break;
       case 'd':
         dict = fopen(optarg, "w");
         break;
       case ':':
         fprintf(stderr, "option: %c need a argument!\n", (char)optopt); 
         fprintf(stderr, "%s\n", usage);
         return -1; 
       case '?':
         fprintf(stderr , "Unknown option %c\n", (char)optopt);
         fprintf(stderr, "%s\n", usage);
         return -1;
     }
   } 

   if (argc < ARGMAX )
   {
     fprintf(stderr, "%s\n", usage);
     return -1;
   }
  
   if( input == NULL || dict == NULL )
   {
     fprintf(stderr, "IO error, please check the filename\n");
     return -1;
   }
  
   /*start here*/ 
   c = fgetc(input);
   if( c == EOF )
   {
     fprintf(stderr, "The input file is empty!\n");
     return -1;
   }

   /*set currw,if the first char is alpah then 
     set currw to 0 ,otherwise, set currw to 1 */
   if( isalpha(c) )
     currw = NON_WORD;
   else
     currw = WORD;
   ungetc(c, input);   
 
   list = make_empty_list(); 
   
   /* Read the file and add word or non-word to list
      and print a sequence of integers
   */ 
   while( (st = parse_file_char(input, &currw)) != NULL )
   {
     if ( (id = (size_t *)find_element(list, st, strcmp_new)) != NULL ) 
     {}
     else
     {
        if ( !insert_at_foot(list, st) )
        {
          fprintf(stderr, "Fail to insert!\n");
          return -1;
        }
        id = (size_t *)find_element(list, st, strcmp_new);  
     } 
     printf("%d\n", (*id)+1 );
   }
 
   generate_dict(dict, list);
    
   return 0;
}


int strcmp_new(const void *str1, const void *str2)
{
   return strcmp( (char*)str1, (char*)str2 );
}
